package main

import (
	"fmt"
	"crypto/aes"
	"crypto/cipher"
	"bytes"

	"encoding/base64"
)

func main() {
	secretKey := []byte("jfsfkshlhglmskllgsfjlafd;e4*23)4")
	//需要去加密的字符串
	plaintext := []byte("wo shi shei a !")

	ciphertext, err := AesEncrypt(plaintext, secretKey)
	if err != nil {
		fmt.Println(err)
	}

	cipherte := Base64Encode(ciphertext)

	fmt.Println(cipherte, "=======1======")


	ciphertext11, err := Base64Decde(cipherte)
	if err != nil {
		fmt.Println("=======3===========")
	}

	tmp, err := AesDecrypt([]byte(ciphertext11), secretKey)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println(string(tmp), "========2=====")

}


//base64 编码
func Base64Encode(value []byte) string {
	encode := base64.StdEncoding.EncodeToString(value)
	return encode
}

//base64解码
func Base64Decde(value string) ([]byte, error) {
	decode, err := base64.StdEncoding.DecodeString(value)
	return decode, err
}


func AesEncrypt(origData, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	origData = PKCS5Padding(origData, blockSize)
	// origData = ZeroPadding(origData, block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	crypted := make([]byte, len(origData))
	// 根据CryptBlocks方法的说明，如下方式初始化crypted也可以
	// crypted := origData
	blockMode.CryptBlocks(crypted, origData)
	return crypted, nil
}

func AesDecrypt(crypted, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	origData := make([]byte, len(crypted))
	// origData := crypted
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS5UnPadding(origData)
	// origData = ZeroUnPadding(origData)
	return origData, nil
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	// 去掉最后一个字节 unpadding 次
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}
